<template>
	<!-- 只有总页码大于1才显示 -->
	<div class="pager-container" v-if="pagerNumber > 1">
		<a @click="handleChange(1)" :class="{ disabled: current === 1 }"
			>|&lt;&lt;</a
		>
		<a @click="handleChange(current - 1)" :class="{ disabled: current === 1 }"
			>&lt;&lt;</a
		><a
			v-for="(n, i) in numbers"
			:key="i"
			@click="handleChange(n)"
			:class="{ active: n === current }"
			>{{ n }}</a
		>
		<a
			@click="handleChange(current + 1)"
			:class="{ disabled: current === pagerNumber }"
			>&gt;&gt;</a
		><a
			@click="handleChange(pagerNumber)"
			:class="{ disabled: current === pagerNumber }"
			>&gt;&gt;|</a
		>
	</div>
</template>

<script>
//分页组件
export default {
	props: {
		current: {
			type: Number,
			required: false,
			default: 1,
		},
		total: {
			type: Number,
			required: false,
			default: 0,
		},
		limit: {
			type: Number,
			required: false,
			default: 10,
		},
		visibleNumber: {
			type: Number,
			required: false,
			default: 10,
		},
	},
	computed: {
		//总页数
		pagerNumber() {
			return Math.ceil(this.total / this.limit);
		},
		//当前页面最小页码
		visibleMin() {
			let min = Math.floor(this.current - this.visibleNumber / 2);
			if (min < 1) {
				min = 1;
			}
			return min;
		},
		//当前页面最大页码
		visibleMax() {
			let max = this.visibleMin + this.visibleNumber - 1;
			if (max > this.pagerNumber) {
				max = this.pagerNumber;
			}
			return max;
		},
		numbers() {
			let nums = [];
			for (let i = this.visibleMin; i <= this.visibleMax; i++) {
				nums.push(i);
			}
			return nums;
		},
	},
	methods: {
		handleChange(newpage) {
			//限制边界
			if (newpage < 1) {
				newpage = 1;
			}
			if (newpage > this.pagerNumber) {
				newpage = this.pagerNumber;
			}
			if (newpage === this.current) {
				return;
			}
			this.$emit("pagechange", newpage);
		},
	},
};
</script>

<style lang="less" scoped>
// 引入变量样式
@import "~@/styles/var.less";
.pager-container {
	display: flex;
	justify-content: center;
	margin: 20px 0;
	a {
		color: @primary;
		margin: 0 6px;
		cursor: pointer;
		&.disabled {
			color: @lightWords;
			cursor: not-allowed;
		}
		&.active {
			color: @words;
			font-weight: bold;
			cursor: text;
		}
	}
}
</style>
